const db = require("../config/db");

class Banner {
  static async getAll() {
    const [rows] = await db.query(
      "SELECT * FROM banners ORDER BY sort_order ASC"
    );
    return rows;
  }

  static async getById(id) {
    const [rows] = await db.query("SELECT * FROM banners WHERE id = ?", [id]);
    return rows[0];
  }

  static async create(bannerData) {
    const {
      title,
      image_url,
      link_url,
      sort_order = 0,
      status = 1,
    } = bannerData;
    const [result] = await db.query(
      "INSERT INTO banners (title, image_url, link_url, sort_order, status) VALUES (?, ?, ?, ?, ?)",
      [title, image_url, link_url, sort_order, status]
    );
    return result.insertId;
  }

  static async update(id, bannerData) {
    const { title, image_url, link_url, sort_order, status } = bannerData;
    const [result] = await db.query(
      "UPDATE banners SET title = ?, image_url = ?, link_url = ?, sort_order = ?, status = ? WHERE id = ?",
      [title, image_url, link_url, sort_order, status, id]
    );
    return result.affectedRows > 0;
  }

  static async delete(id) {
    const [result] = await db.query("DELETE FROM banners WHERE id = ?", [id]);
    return result.affectedRows > 0;
  }

  static async getByPage(offset, limit) {
    const [rows] = await db.query(
      "SELECT * FROM banners ORDER BY sort_order ASC LIMIT ?, ?",
      [offset, limit]
    );
    return rows;
  }

  static async getTotalCount() {
    const [rows] = await db.query("SELECT COUNT(*) as total FROM banners");
    return rows[0].total;
  }
}

module.exports = Banner;
